//
//  BanBu_ThemeManager.m
//  BanBu
//
//  Created by banbu3 on 7/20/13.
//
//

#import "BanBu_ThemeManager.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "BanBu_ChatBackgroundSettingViewController.h"
#import "BanBu_BubbleViewController.h"
#import "BanBu_ChatViewController.h"

#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "NSDictionary_JSONExtensions.h"
#import "ZipArchive.h"
#import "BanBu_MagicDetailViewController.h"

static BanBu_ThemeManager *sigleton = nil;
@implementation BanBu_ThemeManager;


-(void)setThemeName:(NSString *)themeName
{
    if(![_themeName isEqualToString:themeName])
    {
        _themeName = [themeName copy];

        if([_themeName isEqualToString:@"default"])
        {
            _tabbarHeight = 49;
        }
        else
        {
            _tabbarHeight = [self getThemeImage:@"tabbarImage.png"].size.height;
        }

        [[NSNotificationCenter defaultCenter]postNotificationName:kThemeDidChangeNotification object:nil];
        [UserDefaults setValue:[NSString stringWithString:_themeName] forKey:@"currentTheme"];
    }
}

-(NSString *)getThemePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    return [documentDirectory stringByAppendingFormat:@"/themeList/%@/",_themeName];
}


-(UIImage *)getThemeImage:(NSString *)imageName
{
    if(!imageName.length)
    {
        return nil;
    }
    if([_themeName isEqualToString:@"default"]||!_themeName.length)
    {
        return [UIImage imageNamed:imageName];
    }
    else
    {
//        return [UIImage imageWithContentsOfFile:[[self getThemePath] stringByAppendingString:imageName]];
        if([UIImage imageWithContentsOfFile:[[self getThemePath] stringByAppendingString:imageName]])
        {
          
            return [UIImage imageWithContentsOfFile:[[self getThemePath] stringByAppendingString:imageName]];
        }
    }
    return [UIImage imageNamed:imageName];
}

-(void)initRaysource
{
    _netWork = [[ASINetworkQueue alloc]init];
    _netWork.delegate = self;
    _themeDown = [[NSMutableDictionary alloc] init];
    _themeDownLoading = [[NSMutableDictionary alloc] init];
    _themeExitArr = [[NSMutableArray alloc] init];
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    cachePath  = [cachePath stringByAppendingPathComponent:@"themePic"];
    _themePicPath = [cachePath retain];
}

+(BanBu_ThemeManager *)shareInstance
{
    if(sigleton == nil)
    {
        @synchronized(self)
        {
            sigleton = [[self alloc] init];
            [sigleton initRaysource];
        }
    }
    return sigleton;
}
-(void)dealloc
{
    [super dealloc];
    [_themeDown release],_themeDown = nil;
    [_themeDownLoading release],_themeDownLoading = nil;
    [_themeExitArr release],_themeExitArr = nil;
    [_themePicPath release],_themePicPath = nil;
}
//限制当前对象创建多实例
#pragma mark - sengleton setting
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (sigleton == nil) {
            sigleton = [super allocWithZone:zone];
        }
    }
    return sigleton;
}
+ (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)retain
{
    return self;
}

#pragma mark - 下载背景、气泡

//背景部分
-(void)downloadBGButton:(UIButton *)sender
{
    NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
    
    //静态图
    NSString * imageDownPath = [[fileName stringByAppendingPathComponent:@"chat_bg_photo"]stringByAppendingPathComponent:@"bgDown.plist"];
    
    NSMutableDictionary * imageDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
    if ([[NSFileManager defaultManager]fileExistsAtPath:imageDownPath])
    {
        imageDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:imageDownPath];
    }
    NSArray * keyArray = imageDownDic.allKeys;
    
    static int k = 0;
    for (;k<keyArray.count;)
    {
        NSString * key = [keyArray objectAtIndex:k];
        NSDictionary * oneBubbleDic = [imageDownDic valueForKey:key];
        
        NSString * iconUrl = [oneBubbleDic valueForKey:@"iconurl"];
        NSString * imageID = [oneBubbleDic valueForKey:@"id"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:oneBubbleDic];
        
        if ([[oneBubbleDic valueForKey:imageID] intValue]==0)
        {
            //开线程去下载气泡；
            [self downloadBGImage:@[@"j",imageID,iconUrl,@"iconUrl"]];
            [dic setValue:[NSNumber numberWithInt:1] forKey:imageID];//设置下载状态为已下载
            
            [imageDownDic setValue:dic forKey:imageID];
            break;
        }
        else
        {
            k++;
        }
        //不为0、不为1时，说明都下载了，换下一套下载
    }
    if (k>=keyArray.count)
    {
        k=0;
        if (self.chatBGView)
        {
            [self.chatBGView dismissModalView];
        }
    }
    
    [imageDownDic writeToFile:imageDownPath atomically:YES];//写入已下载文件中
}

-(void)downloadBGImage:(NSArray *)imageUrlArray
{
    if (self.netWork == nil)
    {
        ASINetworkQueue *queue = [[ASINetworkQueue alloc]init];
        self.netWork = queue;
        [queue release];
        self.netWork.delegate = self;
    }
    
    [self.netWork setRequestDidFailSelector:@selector(downloadBgFail:)];
    
    
    [self.netWork setRequestDidFinishSelector:@selector(refreshBGView)];

    //获取参数中的气泡信息
    NSString * kind = [imageUrlArray objectAtIndex:0];
    if ([kind isEqualToString:@"j"])
    {
        NSString * imageID = [imageUrlArray objectAtIndex:1];//bubbleID将作为下载气泡的文件夹名和bubbleInfo.plist文件中的bubbleID

                
        NSString * test = [imageUrlArray objectAtIndex:3];
        
        //创建文件夹路径，文件夹名为气泡id，id前缀“bubble_”
        NSString * imagePath =[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_photo"];
        
        NSString * imageFilePath = [imagePath stringByAppendingPathComponent:@"bgInfo.plist"];
        if (![[NSFileManager defaultManager] fileExistsAtPath:imagePath])
        {
            [[NSFileManager defaultManager]createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
        }

        ASIHTTPRequest * request2 = nil;
        ASIHTTPRequest * request1 = nil;
        
        if ([test isEqualToString:@"iconUrl"])
        {
            NSURL * iconUrl = [NSURL URLWithString:[imageUrlArray objectAtIndex:2]];            
            
            //下载小图
            request2 = [[[ASIHTTPRequest alloc]initWithURL:iconUrl] autorelease];
            request2.delegate = self;
            [request2 setRequestMethod:@"GET"];
            NSString * imageIconFileName = [imagePath stringByAppendingPathComponent:[NSString stringWithFormat:@"chat_bg_%@_icon@2x.png",imageID]];
            [request2 setDownloadDestinationPath:imageIconFileName];
            
            [self.netWork addOperation:request2];
        }
        else
        {
            NSURL * imageUrl = [NSURL URLWithString:[imageUrlArray objectAtIndex:2]];
            //创建网络请求
            //下载大图气泡
            request1 = [[[ASIHTTPRequest alloc]initWithURL:imageUrl] autorelease];
            request1.delegate = self;
            [request1 setRequestMethod:@"GET"];
            
            
            NSString * imageFileName = [imagePath stringByAppendingPathComponent:[ NSString stringWithFormat:@"chat_bg_%@.jpg",imageID]];
            [request1 setDownloadDestinationPath:imageFileName];
            
            [self.netWork addOperation:request1];
            [self.netWork setRequestDidFinishSelector:@selector(downloadBGFinish)];
        }
            
        //将下载的的文件夹写入imageInfo.plist文件
        NSMutableDictionary * bubbleDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
        if ([[NSFileManager defaultManager]fileExistsAtPath:imageFilePath])
        {
            bubbleDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:imageFilePath];
        }
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:10];
        [dic setValue:[NSString stringWithFormat:@"chat_bg_%@",imageID] forKey:@"bgName"];
        [dic setValue:[NSString stringWithFormat:@"chat_bg_%@_icon@2x.png",imageID] forKey:@"bgNameicon"];
        [dic setValue:imageID forKey:@"id"];
        
        [bubbleDownDic setValue:dic forKey:[NSString stringWithFormat:@"chat_bg_%@",imageID]];//文件夹名为key，存放气泡信息
        
        [bubbleDownDic writeToFile:imageFilePath atomically:YES];//写入文件
    }
    else
    {        
        NSString * GIFID = [imageUrlArray objectAtIndex:1];//bubbleID将作为下载气泡的文件夹名和bubbleInfo.plist文件中的bubbleID
                
         NSString * test = [imageUrlArray objectAtIndex:3];
        //创建文件夹路径，文件夹名为气泡id，id前缀“bubble_”
        NSString * GIFPath = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_GIF"];
        
        NSString * GIFFilePath = [GIFPath stringByAppendingPathComponent:@"GIFInfo.plist"];
        
        if (![[NSFileManager defaultManager] fileExistsAtPath:GIFPath])
        {
            [[NSFileManager defaultManager]createDirectoryAtPath:GIFPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        //将下载的的文件夹写入GIFInfo.plist文件
        NSMutableDictionary * bubbleDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
        if ([[NSFileManager defaultManager]fileExistsAtPath:GIFFilePath])
        {
            bubbleDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:GIFFilePath];
        }
        
        
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:10];
        [dic setValue:[NSString stringWithFormat:@"chat_bg_%@",GIFID] forKey:@"bgName"];
        
        [dic setValue:GIFID forKey:@"id"];
        
        [bubbleDownDic setValue:dic forKey:[NSString stringWithFormat:@"chat_bg_%@",GIFID]];//文件夹名为key，存放气泡信息
        [dic setValue:[NSString stringWithFormat:@"chat_bg_%@_icon@2x.gif",GIFID] forKey:@"bgNameicon"];
        
        [bubbleDownDic writeToFile:GIFFilePath atomically:YES];//写入文件
        ASIHTTPRequest * request1 = nil;
        ASIHTTPRequest * request2 = nil;
        
        if ([test isEqualToString:@"iconUrl"])
        {
            NSURL * GIFIconUrl = [NSURL URLWithString:[imageUrlArray objectAtIndex:2]];
            //下载小图
            request2 = [[[ASIHTTPRequest alloc]initWithURL:GIFIconUrl] autorelease];
            request2.delegate = self;
            [request2 setRequestMethod:@"GET"];
            NSString * GIFIconFileName = [GIFPath stringByAppendingPathComponent:[NSString stringWithFormat:@"chat_bg_%@_icon@2x.gif",GIFID]];
            [request2 setDownloadDestinationPath:GIFIconFileName];
            [self.netWork addOperation:request2];
        }
        else
        {
            NSURL * GIFUrl = [NSURL URLWithString:[imageUrlArray objectAtIndex:2]];
            //创建网络请求
            request1 = [[[ASIHTTPRequest alloc]initWithURL:GIFUrl] autorelease];
            //下载显示对方消息的气泡
            NSString * imageFileName = [GIFPath stringByAppendingPathComponent:[ NSString stringWithFormat:@"chat_bg_%@.gif",GIFID]];
            [request1 setDownloadDestinationPath:imageFileName];
            request1.delegate = self;
            [request1 setRequestMethod:@"GET"];
            [self.netWork addOperation:request1];
            [self.netWork setRequestDidFinishSelector:@selector(downloadBGFinish)];
        }
    }
    [self.netWork go];
}

//刷新界面
-(void)refreshBGView
{
    if (self.chatBGView)
    {
        [self.chatBGView refreshView];
    }
    
    NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
    //静态图
    NSString * imageDownPath = [[fileName stringByAppendingPathComponent:@"chat_bg_photo"]stringByAppendingPathComponent:@"bgDown.plist"];
    
    NSMutableDictionary * imageDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
    if ([[NSFileManager defaultManager]fileExistsAtPath:imageDownPath])
    {
        imageDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:imageDownPath];
    }
    NSArray * keyArray = imageDownDic.allKeys;
    
    static int i = 0;
    static int j = 0;
    
    for (;i<keyArray.count;)
    {
        NSString * key = [keyArray objectAtIndex:i];
        NSDictionary * oneBubbleDic = [imageDownDic valueForKey:key];
        
        NSString * iconUrl = [oneBubbleDic valueForKey:@"iconurl"];
        NSString * imageID = [oneBubbleDic valueForKey:@"id"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:oneBubbleDic];
        
        if ([[oneBubbleDic valueForKey:imageID] intValue]==0)
        {
            //开线程去下载气泡；
            [self downloadBGImage:@[@"j",imageID,iconUrl,@"iconUrl"]];
            [dic setValue:[NSNumber numberWithInt:1] forKey:imageID];//设置下载状态为已下载
            
            [imageDownDic setValue:dic forKey:imageID];
            break;
        }
        else
        {
            i++;
        }
        //不为0、不为1时，说明都下载了，换下一套下载
    }
    
    [imageDownDic writeToFile:imageDownPath atomically:YES];//写入已下载文件中

    //下载动态图
    if (i>= keyArray.count)
    {
        //动态图
        NSString * GIFDownPath = [[fileName stringByAppendingPathComponent:@"chat_bg_GIF"] stringByAppendingPathComponent:@"GIFDown.plist"];
        
        NSMutableDictionary * GIFeDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
        if ([[NSFileManager defaultManager]fileExistsAtPath:GIFDownPath])
        {
            GIFeDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:GIFDownPath];
        }
        NSArray * keyGIFArray = GIFeDownDic.allKeys;
       
        
        for (;j<keyGIFArray.count;)
        {
            NSString * key = [keyGIFArray objectAtIndex:j];
            NSDictionary * oneBubbleDic = [GIFeDownDic valueForKey:key];
            
            NSString * iconUrl = [oneBubbleDic valueForKey:@"iconurl"];
            NSString * imageID = [oneBubbleDic valueForKey:@"id"];
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:oneBubbleDic];
            
            if ([[oneBubbleDic valueForKey:imageID] intValue] == 0)
            {
                //开线程去下载背景；
                [self downloadBGImage:@[@"d",imageID,iconUrl,@"iconUrl"]];
                [dic setValue:[NSNumber numberWithInt:1] forKey:imageID];//设置下载状态为未下载
                
                [GIFeDownDic setValue:dic forKey:imageID];
                break;
            }
            else
            {
                j++;
            }
        }
        
        [GIFeDownDic writeToFile:GIFDownPath atomically:YES];//写入已下载文件中
        
        
        if (i>=keyArray.count && j>=keyGIFArray.count)
        {
            i = 0;
            j = 0;
            
            if (self.chatBGView)
            {
                [self.chatBGView dismissModalView];
            }
        }
    }
}

-(void)downloadBgFail:(ASIHTTPRequest *)request
{
    if (self.chatBGView)
    {
        [self.bubbleView dismissModalView];
        [TKLoadingView showTkloadingAddedTo:self.chatBGView.navigationController.view title:NSLocalizedString(@"downloadBgFail", nil) activityAnimated:NO duration:2.0f];
        return;
    }
    
//    ASIHTTPRequest * requestSec = [[ASIHTTPRequest alloc] initWithURL:request.url];
//    [requestSec setDownloadDestinationPath:request.downloadDestinationPath];
//    requestSec.delegate = self;
//    [requestSec setRequestMethod:@"GET"];
//    
//    [self.netWork addOperation:requestSec];
//    [self.netWork go];
}

-(void)downloadBigPhoto:(NSString *)photoIndex andPhotoType:(NSString *)JorD
{
    if ([JorD isEqualToString:@"j"])
    {
        NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
        
        NSString * fielPath = [[fileName stringByAppendingPathComponent:@"chat_bg_photo"] stringByAppendingFormat:@"chat_bg_%d",[photoIndex intValue]];
        
        if ([[NSFileManager defaultManager]fileExistsAtPath:fielPath])
        {
            return;
        }
        
        //静态图
        NSString * imageDownPath = [[fileName stringByAppendingPathComponent:@"chat_bg_photo"]stringByAppendingPathComponent:@"bgDown.plist"];
        
        NSDictionary * downLoadDic = [NSDictionary dictionaryWithContentsOfFile:imageDownPath];
                
        NSDictionary * dic = [downLoadDic valueForKey:photoIndex];
        NSString * imageUrl = [dic valueForKey: @"imgurl"] ;
        NSString * imageID = [dic valueForKey:@"id"];
        
        [self downloadBGImage:@[ JorD,imageID,imageUrl,@"imgurl"]];

    }
    else
    {
        NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"];
        
        NSString * fielPath = [[fileName stringByAppendingPathComponent:@"chat_bg_photo"] stringByAppendingFormat:@"chat_bg_%d",[photoIndex intValue]];
        
        if ([[NSFileManager defaultManager]fileExistsAtPath:fielPath])
        {
            return;
        }
        
        //动态图
        NSString * GIFDownPath = [[fileName stringByAppendingPathComponent:@"chat_bg_GIF"] stringByAppendingPathComponent:@"GIFDown.plist"];
        
        NSMutableDictionary * GIFeDownDic = nil;
        GIFeDownDic = [NSDictionary dictionaryWithContentsOfFile:GIFDownPath];
        
        NSDictionary * dic = [GIFeDownDic valueForKey:photoIndex];
        NSString * imageUrl = [dic valueForKey: @"imgurl"] ;
        NSString * imageID = [dic valueForKey:@"id"];
        
        [self downloadBGImage:@[ JorD,imageID,imageUrl,@"imgurl"]];
    }
}

-(void)downloadBGFinish
{
    if (MyAppDataManager.appChatController && MyAppDataManager.appChatController.isStayInChatPage)
    {
        [MyAppDataManager.appChatController setLoading:[NSNumber numberWithInt:2]];
        [MyAppDataManager.appChatController setBGImage];
    }
}


//气泡部分
-(BOOL)downloadBubbleButton:(UIButton *)sender
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    NSString * bubbleDownPath = [fileName stringByAppendingPathComponent:@"bubbleDown.plist"];
    
    NSMutableDictionary * bubbleDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
    if ([[NSFileManager defaultManager]fileExistsAtPath:bubbleDownPath])
    {
        bubbleDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:bubbleDownPath];
    }
    NSArray * keyArray = bubbleDownDic.allKeys;
    
    BOOL bl = NO;
    
    for (NSString * key in keyArray)
    {
        NSDictionary * oneBubbleDic = [bubbleDownDic valueForKey:key];
        NSString * friendBubbleUrl = [oneBubbleDic valueForKey:@"friend"];
        NSString * userBubbleUrl = [oneBubbleDic valueForKey:@"me"];
        NSString * bubbleID = [oneBubbleDic valueForKey:@"id"];
        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:oneBubbleDic];
        
        if (![[oneBubbleDic valueForKey:bubbleID] intValue])
        {
            bl = YES;
            [dic setValue:[NSNumber numberWithInt:1] forKey:bubbleID];//设置下载状态为未下载
            [bubbleDownDic setValue:dic forKey:bubbleID];
            [bubbleDownDic writeToFile:bubbleDownPath atomically:YES];//写入已下载文件中
            //开线程去下载气泡；
            [self downloadBubble:@[friendBubbleUrl,userBubbleUrl,bubbleID]];
            break;
        }
    }
    
    if (!bl)
    {
        if (self.bubbleView)
        {
            [self.bubbleView dismissModalView];
        }
    }
    
    return bl;
}

-(void)downloadBubble:(NSArray *)BubbleUrlArray
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    NSString * bubbleInfoPath = [fileName stringByAppendingPathComponent:@"bubbleInfo.plist"];
    
    //获取参数中的气泡信息
    NSURL * friendBubbleUrl = [NSURL URLWithString:[BubbleUrlArray objectAtIndex:0]];
    NSURL * userBubbleUrl = [NSURL URLWithString:[BubbleUrlArray objectAtIndex:1]];
    NSString * bubbleID = [BubbleUrlArray objectAtIndex:2];//bubbleID将作为下载气泡的文件夹名和bubbleInfo.plist文件中的bubbleID
    
    //创建文件夹路径，文件夹名为气泡id，id前缀“bubble_”
    NSString * bubbleFilePath =[[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"] stringByAppendingPathComponent:[NSString stringWithFormat:@"bubble_%@",bubbleID]];
    
    BOOL isDir = NO;
    if (![[NSFileManager defaultManager] fileExistsAtPath:bubbleFilePath isDirectory:(&isDir)])
    {
        if ([[NSFileManager defaultManager] createDirectoryAtPath:bubbleFilePath withIntermediateDirectories:YES attributes:nil error:nil])
        {
            //将下载的的文件夹写入bubbleInfo.plist文件
            
            NSMutableDictionary * bubbleDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
            if ([[NSFileManager defaultManager]fileExistsAtPath:bubbleInfoPath])
            {
                bubbleDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:bubbleInfoPath];
            }
            
            
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:10];
            [dic setValue:[NSNumber numberWithInt:1] forKey:[NSString stringWithFormat:@"bubble_%@",bubbleID]];//文件夹名位key
            [dic setValue:bubbleID forKey:@"id"];
            
            [bubbleDownDic setValue:dic forKey:[NSString stringWithFormat:@"bubble_%@",bubbleID]];//文件夹名为key，存放气泡信息
            
            [bubbleDownDic writeToFile:bubbleInfoPath atomically:YES];//写入文件
        }
    }
    
    //创建网络请求
    ASIHTTPRequest * request1 = [[[ASIHTTPRequest alloc]initWithURL:friendBubbleUrl] autorelease];
    //下载显示对方消息的气泡
    NSString * friendBubbleFileName = [bubbleFilePath stringByAppendingPathComponent:@"aio_friend_bg_nor@2x.png"];
    [request1 setDownloadDestinationPath:friendBubbleFileName];
    
    //下载显示自己消息的气泡
    ASIHTTPRequest * request2 = [[[ASIHTTPRequest alloc]initWithURL:userBubbleUrl] autorelease];
    NSString * userbubbleFileName = [bubbleFilePath stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
    [request2 setDownloadDestinationPath:userbubbleFileName];
    
    
    if (self.netWork == nil)
    {
        self.netWork = [[[ASINetworkQueue alloc]init] autorelease];
        self.netWork.delegate = self;
    }

    
    request1.delegate = self;
    [request1 setRequestMethod:@"GET"];
    request2.delegate = self;
    [request2 setRequestMethod:@"GET"];
   
    self.netWork.delegate = self;
    [self.netWork addOperation:request1];
    [self.netWork addOperation:request2];
    
    
    [self.netWork setRequestDidFailSelector:@selector(downloadBublleFail:)];
    
    [self.netWork setRequestDidFinishSelector:@selector(refreshBubbleView)];
    
    [self.netWork go];
}

//刷新界面
-(void)refreshBubbleView
{
    static int i = 0;
    i++;
    if (self.bubbleView)
    {
        [self.bubbleView refreshView];
    }
    BOOL bl = YES;
    if (i%2==0)
    {
        bl = [self downloadBubbleButton:nil];
    }
    
    if (!bl)
    {
        if (self.bubbleView)
        {
            [self.bubbleView dismissModalView];
        }
        [self.netWork cancelAllOperations];
    }
}

//下载气泡失败
-(void)downloadBublleFail:(ASIHTTPRequest *)request
{
    if (self.bubbleView)
    {
        [self.bubbleView dismissModalView];
        [TKLoadingView showTkloadingAddedTo:self.bubbleView.navigationController.view title:NSLocalizedString(@"downloadBubbleFail", nil) activityAnimated:NO duration:2.0f];
        return;
    }
}

//获取更多（气泡、背景）
-(void)getMore:(NSString *)query
{
    NSString * jsonfrom = @"";
    NSString *requestUrlStr = [MyAppDataManager.banbuHostIP stringByAppendingString:query];    
    if ([query isEqualToString:BanBu_GetMoreBubbleImage])//气泡下载
    {
//        jsonfrom = @"eyJmYyI6ImdldF9idWJibGVfbGlzdCJ9";//获取更多聊天气泡
//          jsonfrom = @"eyJmYyI6ImdldF9idWJibGVfbGlzdF92MiJ9";//获取更多聊天气泡
        jsonfrom = @"eyJmYyI6ImdldF9idWJibGVfbGlzdF92MyJ9";
    }
    else if([query isEqualToString:BanBu_GetBGMoreList])//背景下载
    {
        jsonfrom = @"eyJmYyI6ImdldF9iZ21vdmllX2xpc3QifQ==";//获取更多聊天背景
    }
    
    requestUrlStr = [requestUrlStr stringByAppendingString:jsonfrom];
    
    if (self.netWork == nil)
    {
        ASINetworkQueue *queue = [[ASINetworkQueue alloc]init];
        self.netWork = queue;
        self.netWork.delegate = self;
        [queue release];
    }
    

    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestUrlStr]];
    request.delegate = self;
    [request setRequestMethod:@"GET"];
    
    __block typeof(self)blockDelegate = self;
    
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSMutableDictionary *respondsDic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSString *resStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
            
            NSError *error = nil;
            if(!resStr.length)
            {
                error = [NSError errorWithDomain:BanBuDataformatError code:123 userInfo:respondsDic];
                [blockDelegate banbuRequestDidFinished:nil error:error];
                return;
            }
            
            NSData *resFrom64 = [NSData dataFromBase64String:resStr];
            
            [respondsDic addEntriesFromDictionary:[NSDictionary dictionaryWithJSONData:resFrom64 error:&error]];
            
            if([[respondsDic valueForKey:@"error"] isEqualToString:@"__loginidinvalid__"])
            {
                [MyAppDelegate goToLogin:[MyAppDataManager  IsInternationalLanguage:@"__loginidinvalid__"]];
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
            else
            {
                // 国际化语言包
                [blockDelegate banbuRequestDidFinished:respondsDic error:error];
            }
        }
    }];
    
    [self.netWork addOperation:request];
    [self.netWork go];
}

//处理返回的数据
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    if(error)
    {
        if(![error.domain isEqualToString:BanBuDataformatError])
        {
        }
        return;
    }
    
    if([[resDic valueForKey:@"ok"] boolValue])
    {
        // 从服务器获取全部的数据
        if ([AppComManager respondsDic:resDic isFunctionData:BanBu_GetMoreBubbleImage])//气泡
        {
            NSArray * bubbleArray = [resDic valueForKey:@"list"];
            self.bubbleCount = bubbleArray.count;
            
            
            NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
            
            if (![[NSFileManager defaultManager ] fileExistsAtPath:fileName])
            {
                [[NSFileManager defaultManager]createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:nil];//创建气泡文件夹
            }
            
            NSString * bubbleDownPath = [fileName stringByAppendingPathComponent:@"bubbleDown.plist"];
            
            NSMutableDictionary * bubbleDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
            
            if ([[NSFileManager defaultManager]fileExistsAtPath:bubbleDownPath])
            {
                bubbleDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:bubbleDownPath];
            }
            else
            {
                if (self.bubbleView)
                {
                    [self.bubbleView setDefaultBubble:self.bubbleCount];
                }
            }
            
            for (NSDictionary * oneBubbleDic in bubbleArray)
            {
                NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:oneBubbleDic];
                
                NSString * bubbleID = [oneBubbleDic valueForKey:@"id"];
                
                if (![bubbleDownDic valueForKey:bubbleID])
                {
                    [dic setValue:[NSNumber numberWithInt:0] forKey:bubbleID];//设置下载状态为未下载
                    
                    [bubbleDownDic setValue:dic forKey:bubbleID];
                }
            }
            
            [bubbleDownDic writeToFile:bubbleDownPath atomically:YES];//写入已下载文件中
            
            //下载图片
            [self downloadBubbleButton:nil];
        }
        else if ([AppComManager respondsDic:resDic isFunctionData:BanBu_GetBGMoreList])//背景
        {
            NSArray * imageArray = [resDic valueForKey:@"list"];//服务器端传回的数据
                        
            NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_photo"];
            
            if (![[NSFileManager defaultManager ] fileExistsAtPath:fileName])
            {
                [[NSFileManager defaultManager]createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:nil];//创建背景文件夹
            }
            
            NSString * imageDownPath = [fileName stringByAppendingPathComponent:@"bgDown.plist"];
            //静态图部分
            NSMutableDictionary * imageDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
            
            if ([[NSFileManager defaultManager]fileExistsAtPath:imageDownPath])
            {
                imageDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:imageDownPath];
            }
            else
            {
                if (self.chatBGView)
                {
                    [self.chatBGView setDefaultImage:imageArray.count - 5];
                }
            }
            
            //动态图部分
            fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"chat_bg_GIF"];
            
            if (![[NSFileManager defaultManager ] fileExistsAtPath:fileName])
            {
                [[NSFileManager defaultManager]createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:nil];//创建背景文件夹
            }
            
            NSString * GIFDownPath = [fileName stringByAppendingPathComponent:@"GIFDown.plist"];
            NSMutableDictionary * GIFDownDic = [NSMutableDictionary dictionaryWithCapacity:10];
            
            if ([[NSFileManager defaultManager]fileExistsAtPath:GIFDownPath])
            {
                GIFDownDic = [NSMutableDictionary dictionaryWithContentsOfFile:GIFDownPath];
            }
            else
            {
                if (self.chatBGView)
                {
                    [self.chatBGView setDefaultGif:5];
                }
            }
            
            
            for (NSDictionary * imageDic in imageArray)
            {
                if ([[imageDic valueForKey:@"kind"] isEqualToString:@"j"])
                {
                    if (![imageDownDic valueForKey:[imageDic valueForKey:@"id"]])//文件中没有该记录
                    {
                        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:imageDic];
                        [dic setValue:[NSNumber numberWithInt:0] forKey:[imageDic valueForKey:@"id"]];//将以id为键，0为value的值写入文件，标示该记录未下载
                        [imageDownDic setValue:dic forKey:[imageDic valueForKey:@"id"]];
                    }
                    
                    [imageDownDic writeToFile:imageDownPath atomically:YES];//写入已下载文件中
                }
                else
                {
                    if (![GIFDownDic valueForKey:[imageDic valueForKey:@"id"]])//文件中没有该记录
                    {
                        NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:imageDic];
                        [dic setValue:[NSNumber numberWithInt:0] forKey:[imageDic valueForKey:@"id"]];//将以id为键，0为value的值写入文件，标示该记录未下载
                        [GIFDownDic setValue:dic forKey:[imageDic valueForKey:@"id"]];
                    }
                    
                    [GIFDownDic writeToFile:GIFDownPath atomically:YES];//写入已下载文件中
                }
            }
            //直接下载
            [self downloadBGButton:nil];
        }
    }
    else
    {
        //ok 为no
        //        NSString * errorInfo = [MyAppDataManager IsInternationalLanguage:[resDic objectForKey:@"error"]];
        
        //        [TKLoadingView showTkloadingAddedTo:self.view title:errorInfo activityAnimated:NO duration:1.0];
    }
}

#pragma mark - 下载主题

-(void)downLoadThemeImageWithURL:(NSString *)_str
{
    if(!self.netWork)
    {
        ASINetworkQueue *queue = [[ASINetworkQueue alloc] init];
        self.netWork = queue;
        self.netWork.delegate = self;
        [queue release];
    }
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:_str]];
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    cachePath  = [cachePath stringByAppendingPathComponent:@"themePic"];
    NSString *path = [cachePath stringByAppendingPathComponent:[_str substringFromIndex:_str.length-10]];
    
    if(![[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    request.delegate = self;
    request.downloadDestinationPath = path;
    [request setRequestMethod:@"GET"];
    [self.netWork addOperation:request];
    [self.netWork go];
    __block typeof(self)blockDelegate = self;
    [request setFailedBlock:^{
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
            [blockDelegate banbuRequestDidFinished:nil error:error];
        }
    }];
    [request setCompletionBlock:^{
        
        if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
        {
        }
    }];
    
}

#pragma mark - 下载魔法表情
-(void)downLoadMagicfaceWithURL:(NSMutableArray *)urlArray atIndex:(NSInteger )index
{
    if (urlArray.count<=index)
    {
        //下载完成
        if (_magicFaceController)
        {
            [TKLoadingView showTkloadingAddedTo:_magicFaceController.navigationController.view title:NSLocalizedString(@"haveDownload", nil) activityAnimated:NO duration:2];
            [_magicFaceController dismissActive];
            return;
        }
        return;
    }
    //获取大图的url
    NSString * url = [[[urlArray objectAtIndex:index] valueForKey:@"big"] retain];
    [urlArray removeObjectAtIndex:0];
    if (url)
    {
        NSString * path = [AppComManager pathForMsgMedia:url cacheFolder:@"MsgImageCache"];
        //下载
        [self downloadMagicFacewithOneUrl:url urlArray:urlArray withPath:path];
    }
}

-(void)downloadMagicFacewithOneUrl:(NSString *)url urlArray:(NSMutableArray *)urlArray withPath:(NSString *)path
{
    //查看是否已下载
    if([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [self downLoadMagicfaceWithURL:urlArray atIndex:0];
        return;
    }
    
    if(!self.netWork)
    {
        ASINetworkQueue *queue = [[ASINetworkQueue alloc] init];
        self.netWork = queue;
        self.netWork.delegate = self;
        [queue release];
    }
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    
    request.delegate = self;
    request.downloadDestinationPath = path;
    [request setRequestMethod:@"GET"];
    [self.netWork addOperation:request];
    [self.netWork go];
    
    __block typeof(urlArray)blockUrlArray = [urlArray retain];
    
    [request setFailedBlock:^{
        
        if (_magicFaceController)
        {
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
            NSLog(@"error:%@",error);
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"network_error", nil) message:nil delegate:_magicFaceController cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"reDownload", nil), nil];
            [alert show];
            [alert release];
        }
        
    }];
    [request setCompletionBlock:^{
        [self downLoadMagicfaceWithURL:blockUrlArray atIndex:0];
    }];
}

#pragma mark - 下载水印相机的水印图片
 //下载水印图片
-(void)downloadWatermarkImage:(NSString *)folderName
{
    NSURL * url  = nil;
    //下载
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    
    request.delegate = self;
    
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"watermark"];
    
    NSString * path = [fileName stringByAppendingPathComponent:folderName];
    request.downloadDestinationPath = path;
    [request setRequestMethod:@"GET"];
    [self.netWork addOperation:request];
    [self.netWork go];
    
    __block NSString * blockFolderName = [folderName retain];
    
    [request setFailedBlock:^{
        
        if (_watermarkController)
        {
            NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
            NSLog(@"error:%@",error);
            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:NSLocalizedString(@"network_error", nil) message:nil delegate:_watermarkController cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"reDownload", nil), nil];
            [alert show];
            [alert release];
        }
        
    }];
    [request setCompletionBlock:^{
        
        [self  decompressing:blockFolderName];
        [self addNewWatermarkInfo:blockFolderName];
    }];

}

//解压图片
-(void)decompressing:(NSString *)folderName
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"watermark"];
    
    //设置解压文件夹的路径
    NSString * unZipPath = [fileName stringByAppendingPathComponent:folderName];
    //初始化ZipArchive
    ZipArchive *zip = [[ZipArchive alloc] init];
    BOOL result;
    
    if ([zip UnzipOpenFile:unZipPath])
    {
        result = [zip UnzipFileTo:unZipPath overWrite:YES];//解压文件
        if (!result)
        {
            //解压失败
        }
        else
        {
            //解压成功
        }
        [zip UnzipCloseFile];//关闭
    }
    [zip release];

}

//将下载的水印图片信息保存到文件中
-(void)addNewWatermarkInfo:(NSString *)folderName
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"watermark"];
    NSMutableDictionary * infoDic;
    NSString * infoPath = [fileName stringByAppendingPathComponent:@"kindinfo.plist"];
    
    if (![FileManager fileExistsAtPath:fileName])
    {
        [FileManager createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:nil];
        infoDic = [NSMutableDictionary dictionaryWithCapacity:5];
    }
    else
    {
        infoDic = [NSMutableDictionary dictionaryWithContentsOfFile:infoPath];
        if (infoDic == nil)
        {
            infoDic = [NSMutableDictionary dictionaryWithCapacity:5];
        }
    }
    [infoDic setValue:@"01.png" forKey:folderName];
    [infoDic writeToFile:infoPath atomically:YES];
}


#pragma mark - 彩蛋
//下载彩蛋图片和语音
-(BOOL)downloadEastereggImage:(NSString *)imageUrl music:(NSString *)musicUrl
{
    NSString * imagePath = [AppComManager pathForMsgMedia:imageUrl cacheFolder:@"PaintedEggshellFolder"];
    NSString * musicPath = [AppComManager pathForMsgMedia:musicUrl cacheFolder:@"PaintedEggshellFolder"];
    BOOL blImage = NO;
    BOOL blMusic = NO;
    
    if(!self.netWork)
    {
        ASINetworkQueue *queue = [[ASINetworkQueue alloc] init];
        self.netWork = queue;
        self.netWork.delegate = self;
        [queue release];
    }
    
    if (![FileManager fileExistsAtPath:imagePath])
    {
        //下载图片
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imageUrl]];
        
        request.delegate = self;
        request.downloadDestinationPath = imagePath;
        [request setRequestMethod:@"GET"];
        
        __block typeof(self)blockDelegate = self;
        
        [request setFailedBlock:^{
            if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
            {
                NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
                [blockDelegate banbuRequestDidFinished:nil error:error];
            }
        }];
        [request setCompletionBlock:^{
            
            if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
            {
                if ([FileManager fileExistsAtPath:musicPath])
                {
                    //都下载完成，可以播放
                    [ThemeManager.chatViewController showSnowView:imagePath musicPath:musicPath];
                }
            }
        }];
        
        [self.netWork addOperation:request];
        [self.netWork go];

    }
    else
    {
        blImage = YES;
    }
    
    if (![FileManager fileExistsAtPath:musicPath])
    {
        //下载语音
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:musicUrl]];
        
        request.delegate = self;
        request.downloadDestinationPath = musicPath;
        [request setRequestMethod:@"GET"];
        
        __block typeof(self)blockDelegate = self;
        
        [request setFailedBlock:^{
            if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
            {
                NSError *error = [NSError errorWithDomain:request.error.domain code:request.error.code userInfo:nil];
                [blockDelegate banbuRequestDidFinished:nil error:error];
            }
        }];
        [request setCompletionBlock:^{
            
            if([blockDelegate respondsToSelector:@selector(banbuRequestDidFinished:error:)])
            {
                if ([FileManager fileExistsAtPath:imagePath])
                {
                    //都下载完成，可以播放
                    [ThemeManager.chatViewController showSnowView:imagePath musicPath:musicPath];
                }
            }
        }];
        
        [self.netWork addOperation:request];
        [self.netWork go];

    }
    else
    {
        blMusic = YES;
    }
    
    return  (blImage & blMusic);
}

@end
